/**
 * 生成分页数据
 * @param {number} currentPage - 当前页码
 * @param {number} totalRecords - 总记录数
 * @param {number} pageSize - 每页记录数
 * @param {number} maxDisplayPages - 最多显示的页码数
 * @returns {Object} 包含分页信息的对象
 */
function pagination(currentPage = 1, totalRecords = 100, pageSize = 10, maxDisplayPages = 5) {
  // 计算总页数
  const totalPages = Math.ceil(totalRecords / pageSize)

  // 确保当前页在合理范围内
  currentPage = Math.max(1, Math.min(currentPage, totalPages))

  // 计算前一页和后一页
  const prevPage = currentPage > 1 ? currentPage - 1 : null
  const nextPage = currentPage < totalPages ? currentPage + 1 : null

  // 返回的分页数据
  const pagination = {
    totalPages: totalPages,
    currentPage: currentPage,
    pages: [],
    hasPrev: currentPage > 1,
    hasNext: currentPage < totalPages,
    prevPage: prevPage, // 前一页页码 (若无则为null)
    nextPage: nextPage, // 后一页页码 (若无则为null)
    startPage: 1, // 首页始终为1
    endPage: totalPages, // 尾页为总页数
  }

  // 如果总页数小于等于最大显示页数，直接显示所有页码
  if (totalPages <= maxDisplayPages) {
    for (let i = 1; i <= totalPages; i++) {
      pagination.pages.push(i)
    }
  } else {
    // 计算左右边界（确保当前页在中间）
    let leftBound = currentPage - Math.floor(maxDisplayPages / 2)
    let rightBound = currentPage + Math.floor(maxDisplayPages / 2)

    // 处理边界情况
    if (leftBound < 1) {
      leftBound = 1
      rightBound = maxDisplayPages
    }

    if (rightBound > totalPages) {
      rightBound = totalPages
      leftBound = totalPages - maxDisplayPages + 1
    }

    // 添加页码和省略号
    if (leftBound > 1) {
      pagination.pages.push(1)
      if (leftBound > 2) {
        pagination.pages.push('...')
      }
    }

    for (let i = leftBound; i <= rightBound; i++) {
      pagination.pages.push(i)
    }

    if (rightBound < totalPages) {
      if (rightBound < totalPages - 1) {
        pagination.pages.push('...')
      }
      pagination.pages.push(totalPages)
    }
  }

  return pagination
}
